package com.qfedu.common.core.interceptor;


import com.qfedu.common.core.annotation.NoLogin;
import com.qfedu.common.core.constants.CommonConstants;
import com.qfedu.common.core.utils.JwtUtils;
import com.qfedu.common.core.utils.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * ---Do First---
 *
 * @author:wellseasun
 * @date:2025/5/22 下午 8:30
 * @desc:
 */
public class LoginInterceptor implements HandlerInterceptor {
    // preHandle：执行时机：访问接口前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // handler表示处理某个请求的处理器对象，
        // 如果是类级别的拦截器，则handler为类对象，如果是方法级别的拦截器，则handler为方法对象

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            boolean annotationPresent = method.isAnnotationPresent(NoLogin.class);
            if (annotationPresent) {
                // 如果使用了注解，直接放行
                return true;
            } else {
                // 没有使用注解，需要从请求头中获取名为LOGIN_TOKEN的token
                String token = request.getHeader(CommonConstants.LOGIN_TOKEN);
                if (token == null || token.isEmpty()) {
                    throw new RuntimeException("请重新登录");
                }
                try {
                    JwtUtils jwtUtils = new JwtUtils();
                    Claims claims = jwtUtils.parseJWT(token);
                    UserUtils.setUid((Integer) claims.get("uid"));
                } catch (Exception e) {
                    throw e;
                }
            }
        }
        return true;
    }



}
